const crypto = require('crypto')
const convert = require('xml-js')
const token = 'token'

const sign = async (ctx, next) => {
  const {
    signature,
    echostr,
    timestamp,
    nonce
  } = ctx.request.query

  // 验证请求是否来自于微信公众平台
  const arr = [timestamp, nonce, token].sort()
  const str = arr.join('')
  const sign = crypto.createHash('sha1').update(str).digest('hex')
  if (sign === signature) {
    // 返回接口调用者
    ctx.body = echostr
  } else {
    ctx.body = 'error'
  }

  await next()
}

const reply = async (ctx, next) => {
  try {
    const body = ctx.request.body
    const js = convert.xml2js(body, {
      compact: true,
      cdataKey: 'value',
      textKey: 'value'
    }).xml

    const result = Object.keys(js).reduce((obj, key) => {
      obj[key] = js[key]['value']
      return obj
    }, {})

    await ctx.render('index', {
      FromUserName: result.FromUserName,
      ToUserName: result.ToUserName
    })
  } catch (err) {
    
  }
}

module.exports = {
  sign,
  reply
}